package
{
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class Maze
	{
		public static const CELL_SIZE:Number = 30;
		public var densityFactor:Number = 1.0;
		public var size:Rectangle;
		public var objects:Vector.<Rectangle>;
		
		public function Maze(size:Rectangle, densityFactor:Number = 1.0)
		{
			this.size = size;
			this.densityFactor = densityFactor;
			this.objects = new Vector.<Rectangle>;
		}
		
		public function generate():void{
			var height:int;
			var width:int; 
			var numObjects:int = Math.floor(Math.pow(size.width,.5));
			var i:int;
			var nextObj:Rectangle;
			
			for(i = 0; i < numObjects; i++){
				nextObj = new Rectangle(0,0, Global.prng.nextIntRange(1,5)*CELL_SIZE, Global.prng.nextIntRange(1,5)*CELL_SIZE);
				var nextPos:Point;
				do{
					nextPos = skipquad.clamp(new Point(Math.floor(Global.prng.nextDoubleRange(size.left, size.right)), 
						Math.floor(Global.prng.nextDoubleRange(size.top, size.bottom))
					),CELL_SIZE);
					nextObj.x = nextPos.x;
					nextObj.y = nextPos.y;
				}while(collides(nextObj));
				
				objects.push(nextObj);
			}
		}

		
		public function draw():Sprite{
			var spr:Sprite = new Sprite();
			spr.graphics.lineStyle(2);
			spr.graphics.drawRect(0, 0, size.width, size.height);
			
			for each(var obj:Rectangle in this.objects){
				var objSpr:Sprite = new Sprite();
				objSpr.graphics.lineStyle(1);
				objSpr.graphics.beginFill(0x000077);
				objSpr.graphics.drawRect(0, 0, obj.width, obj.height);				
				objSpr.graphics.endFill();
				
				spr.addChild(objSpr);
				objSpr.x = obj.x;
				objSpr.y = obj.y;
			}
			
			return spr;
		}
		
		public function collides(obj:Rectangle):Boolean{
			var i:int, il:int;
			
			if(!size.containsRect(obj)){
				return true;
			}
			
			for(i = 0, il = objects.length; i < il; i ++){
				if(objects[i].intersects(obj)){
					return true;
				}
			}
			
			return false;
		}
	}
}